<?php
namespace App\Services;
/**
 * 发送手机短信接口服务
 * Created by PhpStorm.
 * User: yangxiaolin
 * Date: 2017/4/26
 * Time: 9:09
 */
use App\Contracts\SendMsgContracts;
use Illuminate\Support\Facades\Log;

class SendMobileMsgServices implements SendMsgContracts
{
    private $urlParams;
    private $fmt = 'json';
    private $url;
    use HttpRequestServices,MsgTemplate;
    public function __construct()
    {
        $this->url = env('MOBILE_MSG_URL');
        $this->urlParams = [
            'account'=> env('MOBILE_MSG_ACC'),
            'password' =>  env('MOBILE_MSG_PWD'),
            'userid' => env('MOBILE_MSG_ID'),
            'sendTime' => '',
            'action' => 'send',
            'extno' => '',
        ];
    }

    public function send($toUser, $content,$tpl)
    {
        if(empty($toUser)){
            return Log::info('手机号不能为空！');
        }
        if(empty($content))
            return Log::info('短信内容不能为空!');
        $mobileP = '/^1[1-9][0-9]{9}/';
        if(!preg_match($mobileP,$toUser)) {
            return Log::info('手机号格式不正确! '. $toUser);
        }
        $tpl_content = $this->getTpl($tpl);
        $content = vsprintf($tpl_content,explode(',',$content));
        $this->urlParams['mobile'] = $toUser;
        $this->urlParams['content'] = $content;
        return $this->callUrlInterface();
    }
    public function setFmt($fmt = 'json'){
        $this->urlParams['Fmt'] = $fmt;
    }
    private function callUrlInterface()
    {
//        $query = http_build_query($this->urlParams);
        $resp = $this->createRequest($this->url , $this->urlParams, true);
        $send = $this->urlParams;
        unset($send['account']);
        unset($send['password']);
        Log::info(json_encode(['result'=>json_decode($resp,true),'query'=>$send],JSON_UNESCAPED_UNICODE));
        return $resp;
    }
}
